<?php
/**
 * 成就相关API
 * 处理成就列表、用户成就等功能
 */

require_once __DIR__ . '/ApiHandler.php';

class AchievementApi extends ApiHandler {
    
    /**
     * 处理GET请求
     * 获取成就列表或用户成就
     */
    protected function GET() {
        $action = $this->getParam('action', 'list');
        
        switch ($action) {
            case 'list':
                $this->getAchievementList();
                break;
            case 'user':
                $this->getUserAchievements();
                break;
            default:
                $this->sendResponse(['error' => 'Invalid action'], 400);
                break;
        }
    }
    
    /**
     * 处理POST请求
     * 添加用户成就或完成成就
     */
    protected function POST() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        $action = $this->getParam('action', '');
        
        switch ($action) {
            case 'unlock':
                $this->unlockAchievement();
                break;
            default:
                $this->sendResponse(['error' => 'Invalid action'], 400);
                break;
        }
    }
    
    /**
     * 获取成就列表
     */
    private function getAchievementList() {
        $ageGroup = $this->getParam('age_group', 'all');
        $type = $this->getParam('type', '');
        
        $params = [];
        $where = "is_active = 1";
        
        if ($type) {
            $where .= " AND achievement_type = ?";
            $params[] = $type;
        }
        
        $sql = "SELECT * FROM " . DB_PREFIX . "achievements 
                WHERE {$where} 
                ORDER BY points ASC";
        
        $achievements = $this->db->fetchAll($sql, $params);
        
        $this->sendResponse([
            'success' => true,
            'achievements' => $achievements
        ]);
    }
    
    /**
     * 获取用户的成就
     */
    private function getUserAchievements() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        $userId = $this->user->getUserId();
        
        $sql = "SELECT a.*, ua.achieved_at 
                FROM " . DB_PREFIX . "achievements a
                JOIN " . DB_PREFIX . "user_achievements ua ON a.id = ua.achievement_id
                WHERE ua.user_id = ? AND a.is_active = 1
                ORDER BY ua.achieved_at DESC";
        
        $achievements = $this->db->fetchAll($sql, [$userId]);
        
        $this->sendResponse([
            'success' => true,
            'achievements' => $achievements
        ]);
    }
    
    /**
     * 解锁成就
     */
    private function unlockAchievement() {
        // 验证用户登录
        if (!$this->validateAccess()) {
            return;
        }
        
        // 验证必填参数
        if (!$this->validateRequiredParams(['achievement_id'])) {
            return;
        }
        
        $userId = $this->user->getUserId();
        $achievementId = (int)$this->getParam('achievement_id');
        
        // 检查成就是否存在
        $sql = "SELECT * FROM " . DB_PREFIX . "achievements WHERE id = ? AND is_active = 1";
        $achievement = $this->db->fetchRow($sql, [$achievementId]);
        
        if (!$achievement) {
            $this->sendResponse([
                'success' => false,
                'message' => '成就不存在或已禁用'
            ], 404);
            return;
        }
        
        // 检查用户是否已获得该成就
        $sql = "SELECT COUNT(*) FROM " . DB_PREFIX . "user_achievements 
                WHERE user_id = ? AND achievement_id =?";
        $exists = $this->db->fetchOne($sql, [$userId, $achievementId]);
        
        if ($exists) {
            $this->sendResponse([
                'success' => false,
                'message' => '已获得此成就'
            ]);
            return;
        }
        
        // 添加用户成就记录
        try {
            $data = [
                'user_id' => $userId,
                'achievement_id' => $achievementId,
                'achieved_at' => date('Y-m-d H:i:s')
            ];
            
            $this->db->insert('user_achievements', $data);
            
            $this->sendResponse([
                'success' => true,
                'message' => '成就解锁成功',
                'achievement' => $achievement
            ]);
        } catch (PDOException $e) {
            $this->sendResponse([
                'success' => false,
                'message' => '成就解锁失败'
            ], 500);
        }
    }
}

// 创建API实例并处理请求
$api = new AchievementApi('achievements');
$api->processRequest(); 